package com.lenovo.leos.filebrowser.netdisk;

import java.util.List;
import java.util.Map;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lenovo.leos.letools.db.AllUploadTaskEntity;
import com.lenovo.leos.letools.db.FileDownloadEntity;
import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.exception.NetException;
import com.lenovo.leos.letools.exception.PreUploadException;
import com.lenovo.leos.letools.lenovodata.DownLoadServer;
import com.lenovo.leos.letools.lenovodata.UploadServer;
import com.lenovo.leos.filebrowser.R;

public class FileSyncService extends Service {

	private DownLoadServer downLoadServer;
	private UploadServer uploadServer;
	public static final String TAG = "FileSyncService";

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	private final IBinder mBinder = new LocalBinder();

	public class LocalBinder extends Binder {
		FileSyncService getService() {
			return FileSyncService.this;
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		downLoadServer = DownLoadServer.getInstance(getApplicationContext());
		uploadServer =  UploadServer.getInstance(getApplicationContext());
		initNotify();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	public void createFileLoadTask(String fileid, String targetFilePath,
			String fileNewName) throws NetException {
		downLoadServer.createFileLoadTask(fileid, targetFilePath, fileNewName);
	}

	public void createDirLoadTask(String dirid, String dirname,
			String targetFilePath) throws NetException {
		downLoadServer.createDirLoadTask(dirid, dirname, targetFilePath);
	}

	public void pauseDownLoadFileThread(String fileid) {
		downLoadServer.pauseDownLoadFileThread(fileid);
	}

	/**
	 * 暂止一个文件夹下载线程
	 * 
	 * @param fileid
	 */
	public void pauseDownLoadDirThread(String dirid) {
		downLoadServer.pauseDownLoadDirThread(dirid);
	}

	/**
	 * 删除一个文件下载任务
	 */
	public void destroyFileDownLoadThread(String fileid) {
		downLoadServer.destroyFileDownLoadThread(fileid);
	}

	/**
	 * 删除一个文件文件夹下载任务
	 */
	public void destroyDirDownLoadThread(String topDirId) {
		downLoadServer.destroyDirDownLoadThread(topDirId);
	}

	/**
	 * 取出文件所有的下载任务
	 * 
	 * @return
	 */
	public List<FileDownloadEntity> getFileLoadTask() {
		return downLoadServer.getFileLoadTask();
	}

	public FileDownloadEntity getFileLoadTask(String path) {
		return downLoadServer.getFileDownloadEntity(path);
	}
	
	public void startDownLoadThreadByFile(String fileid, final ProgressBar pb,final TextView tv,int fileLen) {
		downLoadServer.startDownLoadThreadByFile(fileid, pb, tv, fileLen);
	}
	
	public void startDownLoadThreadByDir(String dirid, final ProgressBar pb,final TextView tv,int dirLen) {
		downLoadServer.startDownLoadThreadByDir(dirid, pb, tv, dirLen);
	}
	
	

	/**
	 * 取出文件夹所有的下载任务
	 * 
	 * @return
	 */
	public Map<String, List<FileDownloadEntity>> getDirLoadTask() {
		return downLoadServer.getDirLoadTask();
	}
	
	public boolean isDownLoadOver(String strwholepath){
		return downLoadServer.isDownLoadOver(strwholepath);
	}
	
	public void destoryAllTask(List<FileDownloadEntity> fileTasks,Map<String,List<FileDownloadEntity>> dirTasks){
		downLoadServer.destoryAllTask(fileTasks, dirTasks);
	}
	
	public List<FileDownloadEntity> getFilesLoadTask() {
		return downLoadServer.getFileLoadTask();
	}
	public Map<String,List<FileDownloadEntity>> getDirsLoadTask() {
		return downLoadServer.getDirLoadTask();
	}
	public List<FileDownloadEntity> getDirLoadTask(String topDirid){
		return downLoadServer.getDirLoadTask(topDirid);
	}

	/**
	 * 创建一个文件上传任务
	 * 
	 * @param wholePath
	 *            文件路径全称（路径+文件名）
	 * @param parentDirId
	 *            要上传文件到的服务器端的dirid
	 * @param customFileName
	 *            为上传文件自定义的文件名
	 * @param localTopDirWholePath
	 *            文件夹上传用到 文件夹的顶层目录全路径 文件上传时 localTopDirWholePath应该为null
	 * @throws NetException
	 * @throws PreUploadException
	 *             文件预上传产生的异常 如-1，-2，-3，-4
	 */
	public void createTask(String wholePath, String parentDirId,
			String customFileName, String localTopDirWholePath)
			throws NetException, PreUploadException {
		uploadServer.createTask(wholePath, parentDirId, customFileName,
				localTopDirWholePath);
	}
	public FileUploadEntity getFileTask(String wholePath){
		return uploadServer.getFileTask(wholePath);
	}
	public void createDirTask(String dirWholepath, String parentDirId)
			throws NetException, PreUploadException {
		uploadServer.createDirTask(dirWholepath, parentDirId);
	}
	
	public void destoryAllTask(AllUploadTaskEntity allUploadTask){
		uploadServer.destoryAllTask(allUploadTask);
	}

	/**
	 * 开启一个上传文件线程
	 * 
	 * @param dirid
	 *            上传到服务器指定的文件夹id
	 * @param fileNewName
	 *            为上传文件起的新文件名
	 * @param wholePath
	 *            要上传文件的全路径
	 * @param pb
	 */
	public void startUpload(String wholePath, final ProgressBar pb,
			final TextView tv, int fileLength) {
		uploadServer.startUpload(wholePath, pb, tv, fileLength);
	}

	/**
	 * 开启一个上传文件夹线程
	 * 
	 * @param dirWholePath
	 * @param pb
	 */
	public void startDirUpload(String dirWholePath, final ProgressBar pb,
			final TextView tv, int fileLength) {
		uploadServer.startDirUpload(dirWholePath, pb, tv, fileLength);
	}
	
	public boolean isUpLoadOver(String strwholepath){
		return uploadServer.isUpLoadOver(strwholepath);
	}

	/**
	 * 暂停一个文件上传文件线程
	 * 
	 * @param wholePath
	 */
	public void pauseUpload(String wholePath) {
		// 取得对应"文件全路径对应的线程"
		uploadServer.pauseUpload(wholePath);
	}
	
	public List<FileUploadEntity> getDirTask(String localTopDirWholePath){
		return uploadServer.getDirTask(localTopDirWholePath);
	}

	/**
	 * 暂停一个文件夹上传文件线程
	 * 
	 * @param dirWholePath
	 */
	public void pauseDirUpload(String dirWholePath) {
		uploadServer.pauseDirUpload(dirWholePath);
	}

	/**
	 * 删除一个文件上传任务
	 * 
	 * @param wholePath
	 */
	public void destoryFileTask(String wholePath) {
		uploadServer.destoryFileTask(wholePath);
	}

	/**
	 * 删除一个文件夹上传任务
	 * 
	 * @param wholePath
	 */
	public void destoryDirTask(String localTopDirWholePath) {
		uploadServer.destoryDirTask(localTopDirWholePath);
	}

	/**
	 * 得到指定wholePath的任务
	 * 
	 * @param wholePath
	 * @return
	 */
	public FileUploadEntity getTaskByWholePath(String wholePath) {
		return uploadServer.getTaskByWholePath(wholePath);
	}

	private void initNotify() {
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notifyMsg = this.getApplicationContext().getString(
				R.string.notify_string);
		if (null == notification) {
			notification = new Notification(R.drawable.icon, "file sync",
					System.currentTimeMillis());
		}
		if (null == pengdingIntent) {
			pengdingIntent = PendingIntent.getActivity(this, 0,
					new Intent(this, TaskManagerActivity.class), 0);
		}
		
//		showNotify();
	}

	/**
	 * 得到所有的上传任务
	 * 
	 * @return
	 */
	public AllUploadTaskEntity getAllTask() {
		return uploadServer.getAllTask();
	}

	NotificationManager mNM;
	Notification notification;
	PendingIntent pengdingIntent;
	String notifyMsg;

	// show notify
	public void showNotify() {
//		for(int i=0;i<5;i++){
//			Log.d("FileSyncService","############################## FileSyncService,showNotify");
//		}
		int upload_now_num = 0;
		int upload_pause_num = 0;
		int upload_complete_num = 0;

		int download_now_num = 0;
		int download_pause_num = 0;
		int download_complete_num = 0;

		SumTask sumTask = SumTask.getInstance();
		String[] download_total_str = sumTask.getDownloadTaskTotalCount(
				this.getApplicationContext()).split(";");
		String[] upload_total_str = sumTask.getUploadTaskTotalCount(
				this.getApplicationContext()).split(";");

		upload_now_num = Integer
				.parseInt(upload_total_str[SumTask.UPLOAD_RUN_COUNT]);
		upload_pause_num = Integer
				.parseInt(upload_total_str[SumTask.UPLOAD_RUN_COUNT]);
		upload_complete_num = Integer
				.parseInt(upload_total_str[SumTask.UPLOAD_RUN_COUNT]);

		download_now_num = Integer
				.parseInt(download_total_str[SumTask.DOWNLOAD_RUN_COUNT]);
		download_pause_num = Integer
				.parseInt(download_total_str[SumTask.DOWNLOAD_PAUSE_COUNT]);
		download_complete_num = Integer
				.parseInt(download_total_str[SumTask.DOWNLOAD_COMPLETE_COUNT]);

		String contentStr = String.format(notifyMsg, upload_now_num,
				upload_pause_num, upload_complete_num, download_now_num,
				download_pause_num, download_complete_num);
		String title = this.getString(R.string.upload_download_notify_title);
		notification.setLatestEventInfo(this,title,contentStr,
				pengdingIntent);
		mNM.notify(R.string.upload_download_notice,notification);
		
		if(!ShowNotifyThreadStarted){
			mShowNotifyThread.start();
			ShowNotifyThreadStarted = true;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		for(int i=0;i<20;i++){
			Log.d(TAG,"############################## FileSyncService destroyed");
		}
		mNM.cancel(R.string.upload_download_notice);
	}

	public void cancelNotify(){
		if(null != mNM){
			mNM.cancel(R.string.upload_download_notice);
		}
	}
	
	private ShowNotifyThread mShowNotifyThread = new ShowNotifyThread();
	boolean ShowNotifyThreadStarted = false;
	private class ShowNotifyThread extends Thread{
		boolean shouldRun = true;
		@Override
		public void run() {
			super.run();
			while(shouldRun){
				mHandler.sendEmptyMessage(REFRESH_NOTIFY);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public static final int REFRESH_NOTIFY = 1;
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(REFRESH_NOTIFY == msg.what){
				showNotify();
			}
		}
	};
	
	
}
